#include "initialization.h"
#include <unistd.h>
#include "folder.h"
#include <fstream>
#include <cstdio>
#include "log.h"



bool CreateFolder(const std::string &folderpath)
{
  if (!directoryExists(folderpath))
  {
    logMessage(folderpath + " Folder does not exist. Creating...");
    if (createDirectory(folderpath))
    {
      logMessage(folderpath + " Folder created successfully.");
      return true;
    }
    else
    {
      std::cerr << "Failed to create folder!" << std::endl;
      return false;
    }
  }
  return true;
}

bool fileExists(const std::string &filePath)
{
  std::ifstream file(filePath);
  return file.good();
}

bool SystemInitialization()
{

  // 创建日志文件夹
  if (!directoryExists(LogFloderPath))
  {
    if (!createDirectory(LogFloderPath))
    {
      std::cerr << "Failed to create folder!" << std::endl;
      return false;
    }
  }

  // 删除日志文件
  std::remove(LogFilePath.c_str());

  logMessage("\n");
  logMessage("==========:Version Start Work:==========");

  // 检查创建文件夹
  CreateFolder(SaveImageFloderPath);
  CreateFolder(ParamFloderPath);
  CreateFolder(JobFileFloderPath);

  // 基本的配置参数
  ConfigureRead();

  return true;
}

// 基本的配置参数
void ConfigureRead()
{
  Json::Value root;
  Json::Reader reader;
  Json::FastWriter writer;

  std::ifstream file(ConfigureFilePath);
  if (file.is_open())
  {
    file >> root;
    file.close();

    IP = root["IP"].asString();
    Upper_Computer_Port = root["Upper_Computer_Port"].asInt();
    Controller_Port = root["Controller_Port"].asInt();
    Communication_Port = root["Communication_Port"].asInt();

    return;
  }
  else
  {
    root["IP"] = IP;
    root["Upper_Computer_Port"] = Upper_Computer_Port;
    root["Controller_Port"] = Controller_Port;
    root["Communication_Port"] = Communication_Port;

    std::ofstream outFile(ConfigureFilePath, std::ios::out);
    outFile << root;
    outFile.close();

    return;
  }
}
